/*------------------------------------------------------------------
Copyright (c) 2008 visualSingularity.net. All rights reserved.

This file is part of Hyperbolic control.

Hyperbolic control is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.

Hyperbolic control is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------*/

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
using System.Windows.Media;
using System.Windows;
using Hyperbolic.Vectors;

namespace Hyperbolic.Model
{
    /// <summary> The CompositeNodeModel class implements the Composite design pattern for NodeModel.
    /// It represents a NodeModel which is not a leaf.
    /// </summary>
    public class CompositeNodeModel : NodeModel
    {
        #region fields
        private ObservableCollection<NodeModel> _children = new ObservableCollection<NodeModel>();
        private Dictionary<NodeModel, Geodesic> _geodesics = new Dictionary<NodeModel, Geodesic>();
        private double _globalWeight;        
        #endregion

        #region properties

        /// <summary> Gets the children of this node.
        /// </summary>
        public ObservableCollection<NodeModel> Children
        {
            get
            {
                return _children;
            }
        }

        /// <summary> Returns <code>false</code> as this node is an instance of <see cref="CompositeNodeModel"/>.
        /// </summary>
        public override bool IsLeaf
        {
            get
            {
                return false;
            }
        }

        #endregion

        #region ctor

        /// <summary>Constructor for root node.
        /// </summary>
        /// <param name="node">The encapsulated INode.</param>
        /// <param name="model">The tree model using this NodeModel.</param>
        public CompositeNodeModel(IBindingNode node, ITreeModel model)
            : this(node, null, model)
        {

        }

        public CompositeNodeModel(IBindingNode node, CompositeNodeModel parent, ITreeModel model)
            : base(node, parent, model)
        {
            NodeModel __child;
            NodeModel __sibling = null;
            bool __first = true;
            bool __second = false;
            foreach (IBindingNode child in node.Children)
            {
                //instanciates the child
                if (child.IsLeaf)
                {
                    __child = new NodeModel(child, this, model);
                }
                else
                {
                    __child = new CompositeNodeModel(child, this, model);
                }

                //add the child to the children of this node
                this.AddChild(__child);

                //set sibling
                if (__first)
                {
                    __sibling = __child;
                    __first = false;
                    __second = true;
                }
                else if (__second)
                {
                    __child.Sibling = __sibling;
                    __sibling.Sibling = __child;
                    __sibling = __child;
                    __second = false;
                }
                else
                {
                    __child.Sibling = __sibling;
                    __sibling = __child;
                }
            }

            // here the down of the tree is built, so we can compute the weight
            this.ComputeWeight();
        }

        #endregion

        #region methods

        /// <summary> Compute the Weight of this node. 
        /// As the weight is computed with the log of the sum of child's weight, we must have all children built before starting the computing.
        /// </summary>
        private void ComputeWeight()
        {
            foreach (NodeModel child in _children)
                _globalWeight += child.Weight;

            if (_globalWeight != 0.0)
                Weight += Math.Log(_globalWeight);
        }

        private void AddChild(NodeModel child)
        {
            _children.Add(child);
            _geodesics.Add(child, new Geodesic(this.EuclidianCoordinates, child.EuclidianCoordinates));
        }

        /// <summary> Layout this node and its children in the hyperbolic space.
        /// Mainly, divide the width angle between children and put the children at the right angle.
        /// Compute also an optimized length to the children.     
        /// </summary>
        /// <param name="angle"> The angle from the x axis.</param>
        /// <param name="width">The angular width to divide. / 2</param>
        /// <param name="length">The parent-child length.</param>
        public override void Layout(double angle, double width, double length)
        {
            base.Layout(angle, width, length);

            if (this.Parent != null)
            {
                // Compute the new starting angle
                // e(i a) = T(z)oT(zp) (e(i angle))
                EuclidianVector __a = new EuclidianVector(Math.Cos(angle), Math.Sin(angle));
                EuclidianVector __nz = new EuclidianVector(-this.EuclidianCoordinates.X, -this.EuclidianCoordinates.Y);
                __a.Translate(this.Parent.EuclidianCoordinates);
                __a.Translate(__nz);
                angle = __a.Arg();

                // Compute the new width
                // e(i w) = T(-length) (e(i width))
                // decomposed to do it faster :-)
                double __c = Math.Cos(width);
                double __A = 1 + length * length;
                double __B = 2 * length;
                width = Math.Acos((__A * __c - __B) / (__A - __B * __c));
            }

            EuclidianVector __dump = new EuclidianVector();

            int __nbrChild = _children.Count;
            double __l1 = (0.95 - Model.Length);
            double __l2 = Math.Cos((20.0 * Math.PI) / (2.0 * __nbrChild + 38.0));
            length = Model.Length + (__l1 * __l2);

            double __startAngle = angle - width;

            // It may be interesting to sort children by weight instead
            foreach (NodeModel __child in _children)
            {
                double __percent = __child.Weight / _globalWeight;
                double __childWidth = width * __percent;
                double __childAngle = __startAngle + __childWidth;
                __child.Layout(__childAngle, __childWidth, length);
                __startAngle += 2.0 * __childWidth;
            }
        }

        /// <summary> Draws the branches from this node to its children. 
        /// </summary>
        /// <param name="canvas">The graphic canvas.</param>
        public override void DrawBranches(DrawingContext dc)
        {
            if (this.IsExpanded)
            {
                foreach (NodeModel child in _children)
                {
                    this.RebuildGeodesics(child);
                    Geodesic __geodesic = _geodesics[child];
                    if (__geodesic != null)
                    {
                        __geodesic.Draw(dc);
                    }

                    child.DrawBranches(dc);
                }
            }

        }

        /// <summary> Transform this node by the given transformation.
        /// </summary>
        /// <param name="t">The transformation.</param>
        public override void Transform(HyperbolicTransformation t)
        {
            base.Transform(t);

            foreach (NodeModel child in _children)
            {
                child.Transform(t);
                this.RebuildGeodesics(child);
            }
        }

        private void RebuildGeodesics(NodeModel child)
        {
            Geodesic __geodesic = _geodesics[child];
            if (__geodesic != null)
            {
                __geodesic.Refresh(this.Model.ContainerOrigin, this.Model.ContainerBounds);
                __geodesic.Rebuild();
            }
        }

        /// <summary> Ends the translation.
        /// </summary>
        public override void EndTranslation()
        {
            base.EndTranslation();

            foreach (NodeModel child in _children)
            {
                child.EndTranslation();
            }
        }

        #endregion

        #region tostring

        public override string ToString()
        {
            string __result = base.ToString();
            __result += "Children :";
            foreach (NodeModel __child in _children)
                __result += "-> " + __child.Node.Name;
            return __result;
        }

        #endregion
    }
}
